#include "x_log.h"
#include "x_logfile.h"
#include <string>
#include <fstream>

using namespace std;

using namespace x_log;

namespace x_log
{

//目前固定在这个路径下面
static string g_log_cfg = "/tmp/level";
#if 0
void init_cfg(const std::string & output_file, const std::string& cfg_file/* = ""*/)
{
    if (output_file.empty())
    {
        CLogger::setLogOutPut(standOutput);
        CLogger::setFlush(standFlush);
        return;
    }
    else
    {
        CLogger::setLogFileName(output_file);
        CLogger::setLogOutPut(defaultOutPut);
        CLogger::setFlush(defaultFlush);
    }
    if (!cfg_file.empty()) g_log_cfg = cfg_file;
}

void set_log_level_by_config(const string& procName)
{
    if (0 != ::access(g_log_cfg.c_str(), F_OK)) return;
    //获取已存在的配置内容
    ifstream ifs(g_log_cfg.c_str());
    string scfgContent = string(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>());
    ifs.close();
    //数据解析
    vector<string> vLines = x_utils::split_string(scfgContent, "\n", false);
    vector<string>::size_type num = vLines.size();
    string slogLevel;
    for (size_t i = 0; i < num; i++)
    {
        vector<string> vItems = x_utils::sep_str(vLines[i], ":", false);
        if (2 != vItems.size()) continue;
        if (vItems[0] == procName)
        {
           slogLevel = vItems[1];
           break;
        }
    }
    if (slogLevel.empty()) return; //未配置则直接返回,使用默认的INFO级别
    //更新日志级别
    for (int i = 0; i < 6; i++)
    {
        if (0 == strncmp(x_log::LogLevelName[i], slogLevel.c_str(), slogLevel.length()))
        {
            CLogger::setLogLevel(static_cast<CLogger::LogLevel>(i));
            break;
        }
    }
}

//设置日志级别
void set_log_level(const std::string& proc_name, const std::string& log_level)
{
    //获取已存在的配置内容
    ifstream ifs(g_log_cfg.c_str());
    string cfg_content = string(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>());
    ifs.close();
    //数据解析
    std::vector<std::string> lines = x_utils::sep_str(cfg_content, "\n", false);
    vector<string>::size_type num = lines.size();
    bool exist = false;
    for (size_t i = 0; i < num; i++)
    {
        std::vector<std::string> items = x_utils::sep_str(lines[i], ":", false);
        if (2 != items.size()) continue;
        if (items[0] == proc_name)
        {
            lines[i].clear();
            lines[i] += ":" + log_level;
            exist = true;
            break;
        }
    }
    if (!exist)
    {
        lines.emplace_back(proc_name + ":" + log_level);
    }
    ofstream ofs(g_log_cfg.c_str());
    for (const auto& cfg : lines)
    {
        ofs << cfg << "\n";
    }
    ofs.close();
}
#endif
} //namespace x_log



